package com.ews.onlineexchange.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections4.MapUtils;

import com.ews.onlineexchange.model.BestTradeEvaluation;
import com.ews.onlineexchange.model.RequirementDefination;
import com.ews.onlineexchange.service.EntityQuery;
import com.ews.onlineexchange.service.TradeHome;

@Named
@ConversationScoped
public class BestTradeEvaluationOfTradeList extends EntityQuery<BestTradeEvaluation> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	TradeHome							tradeHome;
	
	Map<String, BestTradeEvaluation> 	resultMap;

	@Override
	protected List<Predicate> getRestrictions( CriteriaBuilder cb, Root<BestTradeEvaluation> entity ) {
		
		List<Predicate> restrictions = super.getRestrictions( cb, entity );
		
		restrictions.add( cb.equal( entity.join( "trade" ).get( "id" ), tradeHome.getInstance().getId() ) );
		
		return restrictions; 
		
	}

	public Map<String, BestTradeEvaluation> getResultMap() {
		if ( this.resultMap == null ) {
			resultMap = new HashMap<String,BestTradeEvaluation>();
			for ( BestTradeEvaluation _bte : getResultList() ) {
				this.resultMap.put( _bte.getRequirementDefination().getId(), _bte );
			}
		}
		return resultMap;
	}

	public void initBestChooseEvaluation() {
		tradeHome.setBestTradeEvaluationMap( new HashMap<>() );
		for ( RequirementDefination _rd : tradeHome.getInstance().getBulletin().getDefs() ) {
			BestTradeEvaluation value = MapUtils.getObject( getResultMap(), _rd.getId(), new BestTradeEvaluation() );
			value.setTrade( tradeHome.getInstance() );
			value.setRequirementDefination( _rd );
			tradeHome.getBestTradeEvaluationMap().put( _rd.getId(), value );
		}
	}

	public BestTradeEvaluationOfTradeList() {
		setMaxResults( null );
	}
	
	
	
}
